package com.qf.aop.impl;

import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.qf.aop.annocation.OrderDataSoruce;
import com.qf.common.BusinessException;
import com.qf.common.ShopConstatns;
import com.qf.entity.User;
import com.qf.utils.UserUtils;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.omg.CORBA.INTERNAL;
import org.springframework.stereotype.Component;

@Aspect
@Component
@Slf4j
public class OrderDataSoruceAop {

    // 创建一个ThreadLocal用来管理表的index
//    @Setter
//    @Getter
    private static ThreadLocal<Integer> tabIndexThreadLocal = new ThreadLocal<>();

    public static Integer getTableIndex(){
        return  tabIndexThreadLocal.get();
    }


    @Around(("@annotation(orderDataSoruce)"))
    public Object setDataSource(ProceedingJoinPoint point, OrderDataSoruce orderDataSoruce) throws Throwable {

        log.debug("OederDataSoruceAop");

        // 获取用户Id
        Object[] args = point.getArgs();

        User user = null;
        for (int i = 0; i < args.length; i++) {
            if (args[i] instanceof User) {
                user = (User) args[i];
                break;
            }
        }


        if (user == null) {
            log.warn("user为空所以无法设置数据源，程序使用默认的数据源");
            throw new BusinessException(2002,"用户没有登录");
        }
        // 计算分表的得出index
        Integer tabIndex = ((user.getId() / ShopConstatns.ORDER_DB_SIZE) % ShopConstatns.ORDER_TABLE_SIZE) + 1;

        tabIndexThreadLocal.set(tabIndex);

        // 用户id后四位&数据库的数量
        Integer userIdSuff = Integer.parseInt(UserUtils.getUserIdSuffByUid(user.getId().toString()));

        // 获取数据的编号(0,1)
        Integer index = (userIdSuff % ShopConstatns.ORDER_DB_SIZE) + 1;

        // 设置数据源
        DynamicDataSourceContextHolder.push(ShopConstatns.ORDER_DB_PRE+index);
        log.debug("dbIndex:{}",index);
        log.debug("tabIndex:{}",tabIndex);

        return point.proceed(point.getArgs());
    }

    public static void main(String[] args) {
        int uid = 0045;


        Integer tabIndex = ((uid/ ShopConstatns.ORDER_DB_SIZE) % ShopConstatns.ORDER_TABLE_SIZE) + 1;
        Integer dbIndex = (uid % ShopConstatns.ORDER_DB_SIZE) + 1;
        System.out.println("tabIndex:"+tabIndex);
        System.out.println("dbIndex:"+dbIndex);
    }
}
